package controller

import (
	"github.com/gin-gonic/gin"
	"github.com/kataras/golog"
	model "sdn-executor/model/cli"
	"sdn-executor/service"
	"sdn-executor/utils/erros"
)

func ExecuteCLICmd(c *gin.Context) {
	query := model.Query{}
	if err := c.ShouldBindJSON(&query); err != nil {
		SendResponse(c, erros.New(erros.CodeInvalidQueryParam, err.Error()), nil)
		return
	}

	if e := checkQueryParam(&query); e != nil {
		SendResponse(c, e, nil)
		return
	}

	response, e := service.ExecuteCLICmd(&query)
	if e != nil {
		golog.Error("doHandleCLIRequest failed")
		SendResponse(c, e, nil)
		return
	}
	SendResponse(c, erros.OK, response)
}

func GetCLIResultByRequestID(c *gin.Context) {
	requestId := c.Param("requestId")
	results, err := service.GetCLIResultByRequestID(requestId)
	if err != nil {
		SendResponse(c, err, nil)
		return
	}

	SendResponse(c, erros.OK, results)
}

func checkQueryParam(query *model.Query) *erros.Error {
	if len(query.Cmds) == 0 {
		return erros.New(erros.CodeInvalidQueryParam, "field cmds can not be empty")
	}

	m := make(map[int]struct{})
	for _, v := range query.Cmds {
		if v.Index < 0 {
			return erros.New(erros.CodeInvalidQueryParam, "field index must equal or greater than zero")
		}

		if _, ok := m[v.Index]; ok {
			return erros.New(erros.CodeInvalidQueryParam, "field index must not be duplicate")
		}

		m[v.Index] = struct{}{}
	}

	return nil
}
